

package com.hazelcast.scheduledexecutor.impl;

import com.hazelcast.internal.util.ConstructorFunction;
import com.hazelcast.spi.impl.NodeEngine;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static com.hazelcast.internal.util.ConcurrencyUtil.getOrPutIfAbsent;
import static com.hazelcast.internal.util.Preconditions.checkNotNull;

public abstract class AbstractScheduledExecutorContainerHolder implements ScheduledExecutorContainerHolder {

    final NodeEngine nodeEngine;

    /**
     * Containers for scheduled tasks, grouped by scheduler name
     */
    final ConcurrentMap<String, ScheduledExecutorContainer> containers = new ConcurrentHashMap<>();

    public AbstractScheduledExecutorContainerHolder(NodeEngine nodeEngine) {
        this.nodeEngine = nodeEngine;
    }

    @Override
    public ScheduledExecutorContainer getContainer(String name) {
        checkNotNull(name, "Name can't be null");
        return containers.get(name);
    }

    @Override
    public ScheduledExecutorContainer getOrCreateContainer(String name) {
        checkNotNull(name, "Name can't be null");

        return getOrPutIfAbsent(containers, name, getContainerConstructorFunction());
    }

    public Collection<ScheduledExecutorContainer> getContainers() {
        return Collections.unmodifiableCollection(containers.values());
    }

    public Iterator<ScheduledExecutorContainer> iterator() {
        return containers.values().iterator();
    }

    @Override
    public void destroy() {
        for (ScheduledExecutorContainer container : containers.values()) {
            nodeEngine.getExecutionService().shutdownScheduledDurableExecutor(container.getName());
        }
    }

    @Override
    public void destroyContainer(String name) {
        ScheduledExecutorContainer container = containers.remove(name);
        if (container != null) {
            container.destroy();
        }
    }

    protected abstract ConstructorFunction<String, ScheduledExecutorContainer> getContainerConstructorFunction();
}
